function [y,Rin]=zigzag(x,Rout)
%---------------------------------------------------------
%	[y,Rin]=zigzag(x,Rout) performs zigzaging or inverse zigzaging for 2D DCT.
%
%		x:		input data. When x is a matrix, zigzag is performed.
%							When it is a vector, inverse zigzag is performed.
%		Rout: row number of the output matrix (not required when x is a matrix).
%		Rin:	row number of the input matrix
%		y: 	the output. When x is a matrix (vector), y is a vector (matrix).
%
%	Copyright(c): S.Wang, Dec 25, 1999
%	Reised: Aug 2000
%---------------------------------------------------------
[M,N]=size(x);
Rin=size(x,1);
%=================================================
if M==1 | N==1		% x is vector: inverse zigzaging
%=================================================
   N=length(x)/Rout;M=Rout;
   y=zeros(M,N);
   y(1,1)=x(1,1);
   k=1;
   for l=3:M+N
      if round(l/2)==l/2	% even diagonal
         for m=max(1,l-N):min(M,l-1)
            k=k+1;
            y(m,l-m)=x(k,1);
         end
      else						% odd diagonal
         for m=min(M,l-1):-1:max(1,l-N)
            k=k+1;
            y(m,l-m)=x(k,1);
         end
      end
   end
%=================================================   
else					% x is matrix: zigzaging
%=================================================  
   y=zeros(M*N,1);
   y(1,1)=x(1,1);
   k=1;
   for l=3:M+N
      if round(l/2)==l/2	% even
         for m=max(1,l-N):min(M,l-1)
            k=k+1;
            y(k,1)=x(m,l-m);
         end
      else						% odd
         for m=min(M,l-1):-1:max(1,l-N)
            k=k+1;
            y(k,1)=x(m,l-m);
         end
      end
   end
%=================================================   
end
%=================================================

         
   